import router from './router'
import { useAppStoreWithOut } from '@/store/modules/app'
import type { RouteRecordRaw } from 'vue-router'
import { useTitle } from '@/hooks/web/useTitle'
import { useNProgress } from '@/hooks/web/useNProgress'
import { useAnvilCode } from '@code/components/anvil-code-low-common'
import { usePermissionStoreWithOut } from '@/store/modules/permission'
import { usePageLoading } from '@/hooks/web/usePageLoading'
import { NO_REDIRECT_WHITE_LIST } from '@/constants'
import { useUserStoreWithOut } from '@/store/modules/user'
import { useTagsViewStore } from '@/store/modules/tagsView'
import { getToken } from './utils/auth'
import { ElMessage } from 'element-plus'

const { start, done } = useNProgress()

const { loadStart, loadDone } = usePageLoading()

router.beforeEach(async (to, from, next) => {
  start()
  loadStart()
  const permissionStore = usePermissionStoreWithOut()
  const appStore = useAppStoreWithOut()
  const userStore = useUserStoreWithOut()
  const tagsViewStore = useTagsViewStore()
  if (getToken()) {
    if (to.path === '/login') {
      next({ path: '/' })
    } else {

      if((to.path==='/transDesign' )  && from.path !== '/' ) {
        loadDone()
        window.open( window.location.href.split('#')[0]+'#' + to.fullPath, '_blank');
        return
      }

      const { setAnvilPageId, handleLowCodePageRouter, cacheLowCodePageRouter } = useAnvilCode()
      setAnvilPageId(to)
      if (permissionStore.getIsAddRouters) {
        // 判断是否需要强制修改密码
        if (userStore.userInfo && userStore.userInfo.mustUpdatePwd === 'Y' && to.path !== '/personal/resetPassword'){
          ElMessage({
            message: '请更新密码',
            type: 'warning',
          })
          router.replace('/resetPassword')
        }

        // 每次路由跳转之后更新被缓存的路由地址,用于处理路由地址一致但query参数变化需要更新的场景
        tagsViewStore.updateVisitedView(to)
        handleLowCodePageRouter(to, from, next)

        return
      }
      if (NO_REDIRECT_WHITE_LIST.filter((path) => to.path.includes(path)).length) {
        next()
      }else {
        await userStore.getInfo()
      }
      // 开发者可根据实际情况进行修改
      const roleRouters = userStore.getRoleRouters || []

      // 是否使用动态路由
      if (appStore.getDynamicRouter) {
        appStore.serverDynamicRouter
          ? await permissionStore.generateRoutes('server', roleRouters as AppCustomRouteRecordRaw[])
          : await permissionStore.generateRoutes('frontEnd', roleRouters as string[])
      } else {
        await permissionStore.generateRoutes('static')
      }

      permissionStore.getAddRouters.forEach((route) => {
        router.addRoute(route as unknown as RouteRecordRaw) // 动态添加可访问路由表
      })
      const redirectPath = from.query.redirect || to.path
      const redirect = decodeURIComponent(redirectPath as string)
      const nextData = to.path === redirect ? { ...to, replace: true } : { path: redirect }
      permissionStore.setIsAddRouters(true)
      // 每次getRouters之后将低代码相关页面信息缓存起来
      cacheLowCodePageRouter(permissionStore.getRouters)
      next(nextData)
    }
  } else {
    console.log('to.path', to.path)
    if (NO_REDIRECT_WHITE_LIST.filter((path) => to.path.includes(path)).length) {
      next()
    } else {
      next(`/login?redirect=${to.path}`) // 否则全部重定向到登录页
    }
  }
})

router.afterEach((to) => {
  useTitle(to?.meta?.title as string)
  done() // 结束Progress
  loadDone()
})
